﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;
using System.IO;
using Intorise.Common;
using System.Threading;
using Config;
using Intorise.API;
using System.Drawing.Imaging;

namespace MuBot
{
    public partial class MainWindow : Form
    {
        List<Player> players = new List<Player>();
        List<FightLocation> fightLocation = null;
        System.Windows.Forms.Timer timer = null;
        BotConfig config;
        ConfigWindow configWindow = null;
        Thread checkStatusThread = null;
        DateTime startTime = DateTime.MinValue;
        //ValidateCodeHelper validateCodeHelper = null;

        public MainWindow()
        {
            InitializeComponent();
            config = (BotConfig)ConfigManager.BusinessConfig;
            configWindow = new ConfigWindow();

        }

        public void Init()
        {
            //ConsoleBLL.Enabled = false;
            ConsoleBLL.AddDatetime = true;
            ConsoleBLL.Log = new Loger(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt");
            ThreadPool.SetMaxThreads(1000, 1000);
            timer = new System.Windows.Forms.Timer();
            timer.Interval = config.RefreshInteravl * 1000;
            timer.Tick += new EventHandler(timer_Tick);
            fightLocation = FightLocation.Load();
            //validateCodeHelper = new ValidateCodeHelper(AppDomain.CurrentDomain.BaseDirectory + "\\37code.cds", "zheshijie101");
            //validateCodeHelper = new ValidateCodeHelper(AppDomain.CurrentDomain.BaseDirectory + "37code01.cds", "zheshijie101");
            //Bitmap img = (Bitmap)Bitmap.FromFile("e:\\1.png");
            //var data = File.ReadAllBytes("e:\\1.png");

            //MemoryStream stream = new MemoryStream();
            //img.Save(stream, ImageFormat.Jpeg);
            //data = stream.ToArray();
            //string code = validateCodeHelper.GetVcode(data);
            //MessageBox.Show("验证码：" + code);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.dataGridView1.Refresh();
            var time = DateTime.Now - startTime;
            this.labMessage.Text = "已经用时：" + string.Format("{0}天{1}小时{2}分钟", time.Days, time.Hours, time.Minutes);
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void 加载账户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result;
            string[] fileNames = sender as string[];
            if (fileNames != null)
            {
                result = DialogResult.OK;
            }
            else
            {
                result = this.openFileDialog1.ShowDialog();
                fileNames = this.openFileDialog1.FileNames;
            }

            if (result != DialogResult.OK)
            {
                return;
            }

            //players.Clear();
            for (int i = 0; i < fileNames.Length; i++)
            {
                try
                {
                    FillAccounts(fileNames[i], players, false);
                }
                catch (Exception ex)
                {
                    if (MessageBox.Show("加载账户文件" + fileNames[i] + "时出错，您需要在重新加载这个文件吗？", "加载账户出错", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                    {
                        i--;
                    }
                    ConsoleBLL.WriteLineWaring(ex.Message);
                    ConsoleBLL.WriteLineWaring(ex.StackTrace);
                }
            }

            Player.Master = players[0];
            ConsoleBLL.WriteLineWaring("已加载" + players.Count + "个账户");

            this.playerBindingSource.DataSource = null;
            this.playerBindingSource.DataSource = players;
        }

        public void WriterLineText(string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(x =>
                {
                    this.labMessage.Text = x;
                }), text);
            }
            else
            {
                this.labMessage.Text = text;
            }
        }

        void FillAccounts(string filename, List<Player> list, bool clear)
        {
            if (clear)
            {
                list.Clear();
            }

            StreamReader sr = null;
            try
            {
                sr = new StreamReader(filename, Encoding.Default);
            }
            catch
            {
                throw;
            }
            try
            {
                while (!sr.EndOfStream)
                {
                    string[] items = sr.ReadLine().Split(new char[] { ' ', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if ((items.Length > 4))
                    {
                        if (items[0] == "#") { continue; }
                        Account account = new Account();
                        account.Username = items[0];
                        account.Password = items[1];
                        account.ServerID = items[2];
                        FightLocation location = new FightLocation { MapName = items[3], LocationName = items[4] };
                        var point = fightLocation.Where(x => x.MapName == location.MapName && x.LocationName == location.LocationName).FirstOrDefault();
                        var player = new Player(account, config);
                        if (point != null)
                        {
                            player.FightMapLocation = point;
                            player.FightLocation = point.LocationPoints.LastOrDefault();
                        }
                        else
                        {
                            ConsoleBLL.WriteLineError(string.Format("账户：{0}服务器：{1}设定的挂机地图和挂机地点没找到！", account.Username, account.ServerID));
                        }
                        if (items.Length > 5)
                        {
                            int line = 0;
                            if (int.TryParse(items[5], out line))
                            {
                                player.Line = line;
                            }
                        }
                        if (items.Length > 6)
                        {
                            switch (items[6].ToLower())
                            {
                                case "js":
                                    player.Profession = ProfessionEnum.剑士; break;
                                case "gs":
                                    player.Profession = ProfessionEnum.弓手; break;
                                case "mjs":
                                    player.Profession = ProfessionEnum.魔剑士; break;
                                default:
                                    player.Profession = ProfessionEnum.法师; break;
                            }
                        }
                        list.Add(player);
                    }
                }
                sr.Close();
            }
            catch
            {
                if (sr != null)
                {
                    sr.Close();
                }
                throw;
            }
        }

        private void btnStartAll_Click(object sender, EventArgs e)
        {
            if (players.Count == 0) { return; }
            startTime = DateTime.Now;
            timer.Enabled = true;
            Thread thread = new Thread(new ParameterizedThreadStart(t =>
            {
                foreach (Player x in players)
                {
                    if (x.Status == PlayerStatusEnum.等待 || x.Status == PlayerStatusEnum.停止)
                    {
                        if (x.Login())
                        {
                            x.AutoFight = true;
                            GameHelper.RunThread(x.Play);
                            Thread.Sleep(config.LoginInteravl * 1000);
                        }
                    }
                }
                StartCheckStatus();
            }));
            thread.Start();
        }

        private void btnStopAll_Click(object sender, EventArgs e)
        {
            if (this.btnStopAll.Text == "暂停打怪")
            {
                this.btnStopAll.Text = "继续打怪";
                players.ForEach(x =>
                {
                    x.Pause();
                });
            }
            else
            {
                this.btnStopAll.Text = "暂停打怪";
                players.ForEach(x =>
                {
                    x.Continue();
                });
            }

        }

        private void btnQuitAll_Click(object sender, EventArgs e)
        {
            //timer.Enabled = false;
            StopCheckStatus();
            players.ForEach(x =>
            {
                x.Quit();
            });
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            players.ForEach(x =>
            {
                x.Quit();
            });
            this.Close();
        }

        private void 配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            configWindow.ShowDialog();
            timer.Interval = config.RefreshInteravl * 1000;
            players.ForEach(x => { x.RefreshConfig(); });
        }

        private void CheckStatus(object obj)
        {
            ConsoleBLL.WriteLineInfo("状态检测已开始");
            while (true)
            {
                foreach (Player x in players)
                {
                    if (x.Status == PlayerStatusEnum.等待 || x.Status == PlayerStatusEnum.已断线)
                    {
                        if (x.Login())
                        {
                            x.AutoFight = true;
                            GameHelper.RunThread(x.Play);
                        }
                        Thread.Sleep(config.LoginInteravl * 1000);
                    }
                }
                Thread.Sleep(config.CheckStatusInteravl * 1000);
            }
        }

        private void StartCheckStatus()
        {
            Thread thread = new Thread(new ParameterizedThreadStart(x =>
            {
                StopCheckStatus();
                checkStatusThread = new Thread(new ParameterizedThreadStart(CheckStatus));
                checkStatusThread.IsBackground = true;
                checkStatusThread.Start();
            }));
            thread.Start();
        }

        private void StopCheckStatus()
        {
            if (checkStatusThread != null && checkStatusThread.ThreadState == ThreadState.Running)
            {
                while (checkStatusThread.ThreadState != ThreadState.Aborted && checkStatusThread.ThreadState != ThreadState.Stopped)
                {
                    try
                    {
                        checkStatusThread.Abort();
                    }
                    catch { }
                    Thread.Sleep(100);
                }
                ConsoleBLL.WriteLineInfo("状态检测已停止");
            }
        }

        private void 重新开始ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
            {
                Player player = ((Player)row.DataBoundItem);
                player.Quit();
            }
        }
    }
}
